package cn.gailvlun.gll.presentation.apartment.room;

import android.app.Dialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import org.joda.time.DateTime;

import java.util.Date;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatlib.db.ChatDB2;
import cn.gailvlun.gll.databinding.ActivityTimeSettingBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.apartment.room.CreateRoomReq;
import cn.gailvlun.gll.net.apartment.room.ModifyRoomReq;
import cn.gailvlun.gll.net.apartment.room.Room;
import cn.gailvlun.gll.presentation.apartment.ApartmentDetailActivity;
import cn.gailvlun.gll.presentation.apartment.ApartmentManageActivity;
import cn.gailvlun.gll.presentation.apartment.Constants;
import cn.gailvlun.gll.presentation.apartment.room.vm.TimeSettingViewModel;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.util.DateUtil;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.LogUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import cn.gailvlun.gll.widget.dialog.DatePickerDialog;
import cn.gailvlun.gll.widget.dialog.OnConfirmListener;
import io.realm.Realm;



public class TimeSettingActivity extends BaseActivity {

    public static void openActivity(Context context, CreateRoomReq createRoomReq, int hours) {
        Intent intent = new Intent(context, TimeSettingActivity.class);
        intent.putExtra("data", createRoomReq);
        intent.putExtra(Constants.EXTRA_ROOM_SURVIVAL_HOURS, hours);
        context.startActivity(intent);
    }

    public static void openActivity(Context context, CreateRoomReq createRoomReq, int roomId, int hours) {
        Intent intent = new Intent(context, TimeSettingActivity.class);
        intent.putExtra("data", createRoomReq);
        intent.putExtra("roomId", roomId);
        intent.putExtra(Constants.EXTRA_ROOM_SURVIVAL_HOURS, hours);
        context.startActivity(intent);
    }

    private ActivityTimeSettingBinding mBinding;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_time_setting);
        mBinding.setPresenter(new Presenter());
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.nbv.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                if (mViewModel.isModify()) {
                    if (mBinding.getStartTime() == null || mBinding.getEndTime() == null) {
                        ToastUtil.showShort("请选择时间");
                        return;
                    }

                    final Dialog pd = DialogUtil.showIndeterminate(mContext);
                    mCreateRoomReq.setStart_date(mBinding.getStartTime().getMillis() / 1000);
                    mCreateRoomReq.setClose_time(mBinding.getEndTime().getMillis() / 1000);

                    ModifyRoomReq modifyRoomReq = new ModifyRoomReq();
                    modifyRoomReq.setRoom_id(room.getId());
                    modifyRoomReq.setRoom_name(mCreateRoomReq.getName());
                    modifyRoomReq.setTag(mCreateRoomReq.getTag());
                    modifyRoomReq.setMember_max(mCreateRoomReq.getMember_max());
                    modifyRoomReq.setPic(mCreateRoomReq.getPic());
                    modifyRoomReq.setStart_date_time(mCreateRoomReq.getStart_date());
                    modifyRoomReq.setClose_date_time(mCreateRoomReq.getClose_time());
                    modifyRoomReq.setDesc(mCreateRoomReq.getDesc());

                    HttpMethods.getRoomService()
                            .modifyRoom(modifyRoomReq)
                            .compose(RxUtil.<Room>applyScheduler())
                            .compose(TimeSettingActivity.this.<Room>bindToLifecycle())
                            .subscribe(new HttpSubscriber<Room>() {
                                @Override
                                protected void onSuccess(final Room response) {
                                    ToastUtil.showShort("修改成功");
                                    Realm realm = Realm.getInstance(ChatDB2.INSTANCE.getConfiguration());
                                    realm.executeTransaction(new Realm.Transaction() {
                                        @Override
                                        public void execute(Realm realm) {
                                            realm.insertOrUpdate(response);
                                        }
                                    });
                                    realm.close();
                                    ApartmentDetailActivity.openFromNotification(mContext, response.getId());
                                }

                                @Override
                                protected void onFailure(String errMsg, @Nullable Room response, int code) {
                                    DialogUtil.showError(mContext, errMsg);
                                }

                                @Override
                                protected void onFinish() {
                                    super.onFinish();
                                    pd.dismiss();
                                }
                            });
                } else {
                    
                    if (mBinding.getStartTime() == null || mBinding.getTaskTime() == null
                            || mBinding.getEndTime() == null) {
                        ToastUtil.showLong("请选择时间");
                        return;
                    }

                    final Dialog pd = DialogUtil.showIndeterminate(mContext);

                    mCreateRoomReq.setStart_date(mBinding.getStartTime().getMillis() / 1000);
                    mCreateRoomReq.setTask_time(mBinding.getTaskTime().getMillis() / 1000);
                    mCreateRoomReq.setClose_time(mBinding.getEndTime().getMillis() / 1000);

                    HttpMethods.getRoomService()
                            .createRoom(mCreateRoomReq)
                            .compose(RxUtil.<Room>applyScheduler())
                            .subscribe(new HttpSubscriber<Room>() {
                                @Override
                                protected void onSuccess(final Room response) {
                                    ToastUtil.showShort("成功创建");
                                    Realm realm = Realm.getInstance(ChatDB2.INSTANCE.getConfiguration());
                                    realm.executeTransaction(new Realm.Transaction() {
                                        @Override
                                        public void execute(Realm realm) {
                                            realm.insertOrUpdate(response);
                                        }
                                    });
                                    realm.close();
                                    ApartmentManageActivity.openActivity(mContext);
                                }

                                @Override
                                protected void onFailure(String errMsg, @Nullable Room response, int code) {
                                    DialogUtil.showError(mContext, errMsg);
                                }

                                @Override
                                protected void onFinish() {
                                    super.onFinish();
                                    pd.dismiss();
                                }
                            });
                }
            }
        });
    }

    private CreateRoomReq mCreateRoomReq;
    private TimeSettingViewModel mViewModel;
    private Room room;
    private int roomId;
    private int survivalHours;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        mCreateRoomReq = (CreateRoomReq) getIntent().getSerializableExtra("data");

        roomId = getIntent().getIntExtra("roomId", -1);
        survivalHours = getIntent().getIntExtra(Constants.EXTRA_ROOM_SURVIVAL_HOURS, 0);
        mViewModel = ViewModelProviders.of(this).get(TimeSettingViewModel.class);
        if (roomId != -1) {
            mViewModel.setModify(true);
            room = mViewModel.getRoomById(roomId);

            
            mBinding.setStartTime(new DateTime(room.getStart_datetime()));

            
            Date taskDate = DateUtil.parse(DateUtil.TASK_PATTERN, room.getTask_time());
            mBinding.setTaskTime(new DateTime(taskDate));

            
            mBinding.setEndTime(new DateTime(room.getClose_datetime()));


        }

        if (survivalHours < 24) {
            mBinding.llTask.setVisibility(View.GONE);
            

        }
    }

    public class Presenter {
        
        public void onStartTime() {
            
            DatePickerDialog dpd = new DatePickerDialog(mContext);
            dpd.setTitle("预计开启时间");
            dpd.setRangeDate(DateTime.now().plusDays(1), DateTime.now().plusDays(4));

            dpd.setRangeHourFixMinute(0, 23, 0);
            dpd.setSelectDate(mBinding.getStartTime());
            dpd.setSelectTime(mBinding.getStartTime());
            dpd.setOnConfirmListener(new OnConfirmListener<DatePickerDialog, DateTime>() {
                @Override
                public void onConfirm(DatePickerDialog dialog, DateTime data) {
                    mBinding.setStartTime(data);
                    mBinding.setEndTime(data.plusHours(survivalHours));
                    mBinding.setTaskTime(data.plusMinutes(5));
                    mBinding.invalidateAll();
                }
            });
            dpd.show();
        }

        
        public void onPostTaskTime() {
            
            DatePickerDialog dpd = new DatePickerDialog(mContext);
            dpd.setTitle("打卡任务时间");
            dpd.setRangeHourFixMinute(0, 23, 0);
            dpd.setType(DatePickerDialog.Type.TIME);
            dpd.setSelectTime(mBinding.getTaskTime());
            dpd.setOnConfirmListener(new OnConfirmListener<DatePickerDialog, DateTime>() {
                @Override
                public void onConfirm(DatePickerDialog dialog, DateTime data) {
                    mBinding.setTaskTime(data);
                    mBinding.invalidateAll();
                }
            });
            dpd.show();
        }

        
        public void onEndTime() {
            if (mBinding.getStartTime() == null) {
                ToastUtil.showShort("请先选择房间正式开启时间");
                return;
            }
            DatePickerDialog dpd = new DatePickerDialog(mContext);
            dpd.setTitle("预计关闭时间");
            dpd.setFixDate(mBinding.getStartTime().plusDays(survivalHours));
            dpd.setRangeHourFixMinute(20, 23, 0);
            dpd.setSelectDate(mBinding.getEndTime());
            dpd.setSelectTime(mBinding.getEndTime());
            dpd.setOnConfirmListener(new OnConfirmListener<DatePickerDialog, DateTime>() {
                @Override
                public void onConfirm(DatePickerDialog dialog, DateTime data) {
                    mBinding.setEndTime(data);
                    mBinding.invalidateAll();
                }
            });
            dpd.show();
        }
    }

    public static class Util {
        public static String getStartTime(DateTime dt) {
            if (dt == null) {
                return null;
            }
            return DateUtil.format(DateUtil.NO_SECOND_PATTERN, dt.toDate());
        }

        public static String getTaskTime(DateTime taskTime) {
            if (taskTime == null) {
                return null;
            }
            return DateUtil.format(DateUtil.HOUR_MINUTE_PATTERN, taskTime.toDate());
        }

        public static String getEndTime(DateTime endTime) {
            if (endTime == null) {
                return null;
            }
            return DateUtil.format(DateUtil.NO_SECOND_PATTERN, endTime.toDate());
        }
    }
}
